import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
  router,
  Text,
  Image,
  View,
  ScrollView,
  publishDps,
  showToast,
  Button,
  PageContainer,
} from '@ray-js/ray';
import { Card } from '@/components/card';
import { IconFont } from '@/components';
import Strings from '@/i18n';
import {
  CellGroup,
  Cell,
  ActionSheet,
  Switch,
  DateTimePicker,
  BottomSheet,
} from '@ray-js/smart-ui';
import { useDevice, useProps } from '@ray-js/panel-sdk';
import { useAppConfig } from '@/hooks/useAppConfig';
import { NavBarCustom } from '@/components/NavBarCustom';
import { WeatherBox } from '@/components/weatherBox';
import { AreaAndSwitch } from '@/components/areaAndSwitch';
import LoopMode from '@/components/loop-mode';

import { Picker } from '@/components/picker';
import { getCachedSystemInfo } from '@/api/getCachedSystemInfo';
// @ts-ignore
import { BotBar } from '@/components/bot-bar';
import { useThrottleFn } from 'ahooks';

import { BottomButton } from '@/components/BottomButton';
import {
  decodeNormalTimer,
  formatTimeString,
  NormalTimerData,
  putTimerData,
  toLoopBinString,
  toLoopDecimal,
  decodeCycleTimer,
  CycleTimerData,
} from '@/utils/timer';
import { useSwitchInfo } from '@/hooks/useSwitchInfo';
import { differenceWith } from 'lodash-es';
import dayjs from 'dayjs';
import Weeks from '@/components/weeks';
import { DoublePicker } from '@/components/doulePicker';
import AreaSet from '../AddNormal/AreaSelect';
import styles from './index.module.less';

const { safeArea } = getCachedSystemInfo();

const { height } = safeArea;

const getState = (query: { isEdit?: string; id?: string }, timerList: CycleTimerData[]) => {
  if (query.isEdit === 'true') {
    const item = timerList.find(item => String(item.id) === query.id);
    if (item) {
      return {
        startTime: {
          hour: Math.floor(item.startTime / 60),
          minute: item.startTime % 60,
        },
        endTime: {
          hour: Math.floor(item.endTime / 60),
          minute: item.endTime % 60,
        },
        waterTime: item.waterTime,
        waterArea: item.waterArea,
        pauseTime: item.pauseTime,
        loops: item.loops.map(Number) || [0, 0, 0, 0, 0, 0, 0],
      };
    }
  }

  return {
    startTime: { hour: 0, minute: 0 },
    endTime: { hour: 0, minute: 0 },
    waterTime: 1,
    waterArea: undefined,
    pauseTime: 1,
    loops: [0, 0, 0, 0, 0, 0, 0],
  };
};

export function Home({
  location,
}: {
  location: {
    query: {
      isEdit?: string;
      id?: string;
    };
  };
}) {
  const { query } = location;

  const {
    smart_switch: smartSwitch,
    general_timing: generalTiming,
    cycle_timing1: cycleTiming1,
    cycle_timing2: cycleTiming2,
  } = useProps();

  const props = useProps();

  const dpsInfo = useSwitchInfo();

  const durgDps = ['countdown_2', 'countdown_4', 'countdown_6', 'usb_countdown_2', 'countdown_10'];

  const cycleDataSource1 = decodeCycleTimer(cycleTiming1, true, dpsInfo);
  const cycleDataSource2 = decodeCycleTimer(cycleTiming2, true, dpsInfo);

  const cycleDataSource = [...cycleDataSource1, ...cycleDataSource2];
  const normalDataSource = decodeNormalTimer(generalTiming, true, dpsInfo);

  const isEdit = query?.isEdit === 'true';

  const waterTimeRef = useRef('00:01');

  const pauseTimeRef = useRef('00:01');

  const initState = getState(query, cycleDataSource);

  const [startTime, setStartTime] = useState(initState.startTime);

  const [endTime, setEndTime] = useState(initState.endTime);

  const [waterTime, setWaterTime] = useState(initState.waterTime);

  const [pauseTime, setPauseTime] = useState(initState.pauseTime);

  const [waterArea, setwaterArea] = useState(initState.waterArea);

  const [areaSelectShow, setAreaSelectShow] = useState(false);

  const [showBottomPopup, setShowBottomPopup] = useState(false);

  const [showPauseTimePicker, setShowPauseTimePicker] = useState(false);

  const [loops, setLoops] = useState(initState.loops);

  const handleSaveTimer = () => {
    const orginIds = new Array(42).fill(0).map((item, index) => index);

    const exitIds = cycleDataSource.map(item => item.id) || [];

    const newIndex = differenceWith(orginIds, exitIds)[0];

    // todo start time  end time

    if (!isEdit && cycleDataSource?.length >= 42) {
      showToast({
        icon: 'error',
        title: Strings.getLang('maxCycleTimers'),
      });
      return;
    }

    if (waterTime === 0) {
      showToast({
        icon: 'error',
        title: Strings.getLang('water_time_cannot_be_zero'),
      });
      return;
    }

    if (waterArea === undefined) {
      showToast({
        icon: 'error',
        title: Strings.getLang('water_area_cannot_be_empty'),
      });
      return;
    }

    if (
      Number(startTime.hour) * 60 + Number(startTime.minute) >
      Number(endTime.hour) * 60 + Number(endTime.minute)
    ) {
      showToast({
        icon: 'error',
        title: Strings.getLang('start_time_must_be_earlier_than_end_time'),
      });
      return;
    }

    const timeDuration =
      Number(endTime.hour) * 60 +
      Number(endTime.minute) -
      Number(startTime.hour) * 60 -
      Number(startTime.minute);

    if (waterTime + pauseTime > timeDuration) {
      showToast({
        icon: 'error',
        title: Strings.getLang('time_duration_must_be_longer_than_water_time'),
      });
      return;
    }

    console.log('circle', {
      id: isEdit ? query?.id : newIndex,
      power: true,
      loops,
      waterTime,
      pauseTime,
      waterArea,
      startTime: Number(startTime.hour) * 60 + Number(startTime.minute),
      endTime: Number(endTime.hour) * 60 + Number(endTime.minute),
    });

    putTimerData({
      key: 'cycleTiming',
      data: {
        id: isEdit ? query?.id : newIndex,
        power: true,
        loops,
        waterTime,
        pauseTime,
        waterArea,
        startTime: Number(startTime.hour) * 60 + Number(startTime.minute),
        endTime: Number(endTime.hour) * 60 + Number(endTime.minute),
      },
      isEdit,
      normalDataSource,
      cycleDataSource,
      callback: (isReject: boolean, conflictTip = '') => {
        if (isReject) {
          showToast({
            title: conflictTip,
            icon: 'error',
          });
        } else {
          showToast({
            title: Strings.getLang('save_success'),
          });
          router.back();
        }
      },
    });
  };

  const renderPicker = () => (
    <DoublePicker
      time1={startTime}
      time2={endTime}
      handlePickerChange={val => {
        setStartTime(val);
      }}
      handleTime2Change={val => {
        setEndTime(val);
      }}
      is24
    />
  );

  // 渲染灌溉时间模块
  const renderContent = () => {
    const list = [
      {
        type: 'waterArea',
        value:
          waterArea === undefined
            ? Strings.getLang('please_select_area')
            : dpsInfo[waterArea]?.name,

        onClick: () => {
          setAreaSelectShow(true);
        },
        border: false,
      },
      {
        type: 'waterTime',
        value: formatTimeString(waterTime),
        onClick: () => {
          if (dpsInfo[waterArea].timerDpName && durgDps.includes(dpsInfo[waterArea].timerDpName)) {
            return;
          }
          setShowBottomPopup(true);
        },
        border: true,
      },

      {
        type: 'pauseTime',
        value: formatTimeString(pauseTime),
        onClick: () => {
          setShowPauseTimePicker(true);
        },
        border: true,
      },
    ];

    return (
      <View className={styles.optionContainer}>
        {list.map(item => (
          <Cell
            key={item.type}
            title={Strings.getLang(item.type)}
            value={item.value}
            isLink
            onClick={item.onClick}
            border={item.border}
            customClass={
              dpsInfo[waterArea]?.timerDpName &&
              (durgDps.includes(dpsInfo[waterArea]?.timerDpName) || waterArea === undefined) &&
              item.type === 'waterTime'
                ? styles.disabled
                : ''
            }
          />
        ))}
      </View>
    );
  };

  const renderWeek = () => (
    <View className={styles.weekContainer}>
      <View className={styles.weekText}>
        <Text>{Strings.getLang('weekly_cycle')}</Text>
      </View>
      <Weeks
        weeks={loops}
        onChange={weeks => {
          setLoops(weeks);
        }}
      />
    </View>
  );
  return (
    <View className={styles.view}>
      <NavBarCustom name={Strings.getLang(isEdit ? 'edit_timer' : 'add_timer')} back />

      <ScrollView>
        {renderPicker()}

        {renderContent()}

        {renderWeek()}
      </ScrollView>

      <View className={styles.saveBtn} onClick={handleSaveTimer}>
        <Text style={{ color: '#fff', fontSize: '32rpx' }}>{Strings.getLang('save')}</Text>
      </View>

      <BottomSheet
        show={areaSelectShow}
        title={Strings.getLang('waterArea')}
        onClose={() => {
          setAreaSelectShow(false);
        }}
      >
        <AreaSet
          value={waterArea}
          setValue={diy => {
            setAreaSelectShow(false);

            if (durgDps.includes(dpsInfo[diy]?.timerDpName)) {
              setWaterTime(props[dpsInfo[diy]?.timerDpName]);
            }
            setwaterArea(diy);
          }}
        />
      </BottomSheet>

      <BottomSheet
        show={showBottomPopup}
        title={Strings.getLang('waterTime')}
        iconColor="transparent"
        // @ts-ignore
        onClose={() => {
          setShowBottomPopup(false);
        }}
      >
        {showBottomPopup ? (
          <DateTimePicker
            type="time"
            maxHour={3}
            value="00:01"
            showToolbar={false}
            onInput={e => {
              waterTimeRef.current = e.detail;
            }}
            // formatterMap={{
            //   hour: Strings.getLang('hour'),
            // }}

            locale={{
              hour: Strings.getLang('hour'),
              minute: Strings.getLang('min'),
            }}
          />
        ) : null}

        <BottomButton
          handleConfirm={() => {
            const time = waterTimeRef.current.split(':');
            setWaterTime(Number(time[0]) * 60 + Number(time[1]));
            waterTimeRef.current = '00:01';
            setShowBottomPopup(false);
          }}
          handleCancel={() => {
            waterTimeRef.current = '00:01';
            setShowBottomPopup(false);
          }}
        />
      </BottomSheet>

      <BottomSheet
        show={showPauseTimePicker}
        title={Strings.getLang('pauseTime')}
        iconColor="transparent"
        // @ts-ignore
        onClose={() => {
          setShowPauseTimePicker(false);
        }}
      >
        {showPauseTimePicker ? (
          <DateTimePicker
            type="time"
            maxHour={23}
            minMinute={0}
            value="00:01"
            showToolbar={false}
            onInput={e => {
              pauseTimeRef.current = e.detail;
            }}
            locale={{
              hour: Strings.getLang('hour'),
              minute: Strings.getLang('min'),
            }}
          />
        ) : null}

        <BottomButton
          handleConfirm={() => {
            const time = pauseTimeRef.current.split(':');
            setPauseTime(Number(time[0]) * 60 + Number(time[1]));
            pauseTimeRef.current = '00:01';
            setShowPauseTimePicker(false);
          }}
          handleCancel={() => {
            pauseTimeRef.current = '00:01';
            setShowPauseTimePicker(false);
          }}
        />
      </BottomSheet>
    </View>
  );
}

export default Home;
